import { Inject, Injectable } from '@nestjs/common';
import { FindBookDto } from './dto/find-book.dto';
import { CreateBookDto } from './dto/create-book.dto';
import { DbService } from 'src/db/db.service';
import { Book } from './entities/book.entity';

@Injectable()
export class BookService {
  @Inject(DbService)
  private dbService: DbService;
  async list(body: FindBookDto) {
    const { id = '' } = body;
    const books: Book[] = await this.dbService.read();
    if (!id) {
      return books;
    }
    return {
      book:
        books.find((v) => {
          return v.id === id;
        }) || [],
    };
  }
  async create(body: CreateBookDto) {
    const { id } = body;
    const books: Book[] = await this.dbService.read();
    const foundBook = books.find((v) => {
      return v.id === id;
    });
    if (foundBook) {
      return {
        message: '当前书籍已存在',
      };
    }
    books.push(body);
    await this.dbService.write(books);
    return {
      message: '新增成功',
    };
  }
  async update(body: CreateBookDto) {
    const { id } = body;
    let books: Book[] = await this.dbService.read();
    const foundBook = books.find((v) => {
      return v.id === id;
    });
    if (!foundBook) {
      return {
        message: '该本书不存在',
      };
    }
    books = books.filter((v) => {
      return v.id !== id;
    });
    books.push(body);
    await this.dbService.write(books);
    return {
      message: '修改成功',
    };
  }
  async delete(body: FindBookDto) {
    const { id } = body;
    let books: Book[] = await this.dbService.read();
    const foundBook = books.find((v) => {
      return v.id === id;
    });
    if (!foundBook) {
      return {
        message: '该本书不存在',
      };
    }
    books = books.filter((v) => {
      return v.id !== id;
    });
    await this.dbService.write(books);
    return {
      message: '删除成功',
    };
  }
}
